package com.linkage.jz.bankruptcy.activity.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.RegistLogin.AccountLoginActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class PermissionActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = AccountLoginActivity.class.getSimpleName();

    private static MyProInfo mInfo;
    private ShapeLoadingDialog shapeLoadingDialog;

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        top_back.setOnClickListener(this);
        top_mune.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        top_title = findViewById(R.id.top_title);
        top_title.setText("设置公开栏目");
//        top_mune.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initView() {

    }

    Button btn_login, getcode;
    TextView top_title;
    TextView select_all;
    Button top_back, top_mune;

    CheckBox pro_xm, pro_jd, pro_zq, pro_bj, pro_tl, pro_rw, pro_gs;

    public static void start(Context context, MyProInfo info) {
        Intent intent = new Intent(context, PermissionActivity.class);
        mInfo = info;
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_project_permission);

        initview();
        initTitle();
        initData();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        super.onCreate(savedInstanceState);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层


        top_back = findViewById(R.id.top_back);
        top_mune = findViewById(R.id.top_mune);

        top_mune.setVisibility(View.VISIBLE);
        top_mune.setText("完成");

        select_all = findViewById(R.id.select_all);
        select_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pro_xm.setChecked(true);
                pro_jd.setChecked(true);
                pro_zq.setChecked(true);
                pro_bj.setChecked(true);
                pro_tl.setChecked(true);
                pro_rw.setChecked(true);
                pro_gs.setChecked(true);
            }
        });

        pro_xm = findViewById(R.id.pro_xm);
        pro_jd = findViewById(R.id.pro_jd);
        pro_zq = findViewById(R.id.pro_zq);
        pro_bj = findViewById(R.id.pro_bj);
        pro_tl = findViewById(R.id.pro_tl);
        pro_rw = findViewById(R.id.pro_rw);
        pro_gs = findViewById(R.id.pro_gs);

        String section = mInfo.getPublicSection();
        if (!"".equalsIgnoreCase(section)) {
            String[] sp_section = section.split(",");
            for (int i = 0; i < sp_section.length; i++) {
                String tmp = sp_section[i];
                if ("0".equalsIgnoreCase(tmp)) {
                    pro_xm.setChecked(true);
                }
                if ("1".equalsIgnoreCase(tmp)) {
                    pro_jd.setChecked(true);
                }
                if ("2".equalsIgnoreCase(tmp)) {
                    pro_zq.setChecked(true);
                }
                if ("3".equalsIgnoreCase(tmp)) {
                    pro_bj.setChecked(true);
                }
                if ("4".equalsIgnoreCase(tmp)) {
                    pro_tl.setChecked(true);
                }
                if ("5".equalsIgnoreCase(tmp)) {
                    pro_rw.setChecked(true);
                }

                if ("6".equalsIgnoreCase(tmp)) {
                    pro_gs.setChecked(true);
                }

            }
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                finish();
                break;
            case R.id.top_mune:
                saveData();
                break;
            default:
                break;
        }
    }

    public void saveData() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken();
            return;
        }

        String str = "";
        if (pro_xm.isChecked()) {
            str = "0";
        }

        if (pro_xm.isChecked()) {
            if (!"".equalsIgnoreCase(str)) {
                str += ",";
            }
            str += "1";
        }
        if (pro_zq.isChecked()) {
            if (!"".equalsIgnoreCase(str)) {
                str += ",";
            }
            str += "2";
        }
        if (pro_bj.isChecked()) {
            if (!"".equalsIgnoreCase(str)) {
                str += ",";
            }
            str += "3";
        }
        if (pro_tl.isChecked()) {
            if (!"".equalsIgnoreCase(str)) {
                str += ",";
            }
            str += "4";
        }
        if (pro_rw.isChecked()) {
            if (!"".equalsIgnoreCase(str)) {
                str += ",";
            }
            str += "5";
        }
        if (pro_gs.isChecked()) {
            if (!"".equalsIgnoreCase(str)) {
                str += ",";
            }
            str += "6";
        }


        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() / 1000 + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        mInfo.setPublicSection(str);
        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString("saveCid", "");
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
//                .add("appVersion", "0.0.1")

                .add("addRole", mInfo.getAddRole())
                .add("id", mInfo.getId())
                .add("debtorName", mInfo.getDebtorName())
                .add("projectStatus", mInfo.getProjectStatus())
                .add("projectType", mInfo.getProjectType())
                .add("projectName", mInfo.getProjectName())
                .add("projectLogo", mInfo.getProjectLogo())
                .add("projectNote", mInfo.getProjectNote())
                .add("courtName", mInfo.getCourtName())
                .add("caseNumber", mInfo.getCaseNumber())
                .add("debtorLegalRepresentative", mInfo.getDebtorLegalRepresentative())
                .add("sysAddressId", mInfo.getSysAddressId())
//                .add("allowJoin",  mInfo.getAllowJoin())
//                .add("publicStatus",  mInfo.getPublicStatus())
                .add("publicStatus", "0")
                .add("allowJoin", "true")
                .add("publicSection", str)
                .add("close", mInfo.getClose())

                .add("closeClaimFiling", mInfo.getCloseClaimFiling())
                .add("openDiscussion", mInfo.getOpenDiscussion())
                .add("allowCreditorsChangInfo", mInfo.getAllowCreditorsChangInfo())
                .add("displayedInstantly", mInfo.getDisplayedInstantly())
                .add("creditorsVisibleDetails", mInfo.getCreditorsVisibleDetails())
                .add("openAdministratorList", mInfo.getOpenAdministratorList())

                .add("openAdministratorInfo", mInfo.getOpenAdministratorInfo())
                .add("openCreditorsList", mInfo.getOpenCreditorsList())
                .add("openCreditorsInfo", mInfo.getOpenCreditorsInfo())

                .add("managerListStr", mInfo.getManagerListStr())
                .add("debtorYyzzFileListStr", mInfo.getDebtorYyzzFileListStr())
                .add("courtSlwsFileListStr", mInfo.getCourtSlwsFileListStr())
                .add("courtManagerFileListStr", mInfo.getCourtManagerFileListStr())
                .add("otherFileListStr", mInfo.getOtherFileListStr())


                .build();

        String url = Consts.WEBURL_SETPRORIGHTS;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
//                        Gson gson = new Gson();
//                        JSONObject data = object.getJSONObject("data");
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                EventBus.getDefault().post(mInfo);
                                Toast.makeText(PermissionActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                                finish();
                            }

                        });

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(PermissionActivity.this, "更新失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }

                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }


}
